import {Component, OnInit} from '@angular/core';
import {HttpClient, HttpParams} from "@angular/common/http";
import {HeroService} from "../hero.service";
import {User} from "../user";
import {AppModule} from "../app.module";
import {TokenService} from "../token.service";

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})

export class LoginComponent implements OnInit {

  heroes;
  model = new User();

  constructor(private http: HttpClient, private heroService: HeroService, private tokenService: TokenService) {
  }

  action = AppModule.BASE_NET_URL_LOCAL + "/user/login";
  action1 = AppModule.BASE_NET_URL_LOCAL + "/auth/login";

  ngOnInit() {
    this.getHeroes();
  }

  getHeroes(): void {
    this.heroService.getHeroes()
      .subscribe(heroes => this.heroes = heroes);
  }

  submitted = false;


  onSubmit() {
    this.http.post("http://193.112.113.194:8769/store/auth/login", {}, {params: new HttpParams().set('username', this.model.username).set('password', this.model.password)}).subscribe(data => {
      localStorage.setItem('name', this.model.username);
      localStorage.setItem('word', this.model.password);
      localStorage.setItem('token', data['token']);
      this.tokenService.refreshToken();
      location.href = '/back';
      err => {
        location.href = '/login';
      }
    })
  }

}
